package com.example.servicedemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/**
 * 
 * @author fulishang
 * 
 */
public class ServiceDemoActivity extends Activity {

	private static final String TAG = "ServiceDemoActivity";

	private Button bindButton;
	private Button startButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		bindButton = (Button) findViewById(R.id.bindServiceButton);
		startButton = (Button) findViewById(R.id.startServiceButton);

		bindButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(TAG, "Click the bind button...");
				Toast.makeText(ServiceDemoActivity.this, "Step 1, step in to bind...", Toast.LENGTH_SHORT).show();
				bindService(new Intent(ServiceDemo.ACTION), conn,
						BIND_AUTO_CREATE);
			}

		});

		startButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				Log.d(TAG, "Click the start button...");
				startService(new Intent(ServiceDemo.ACTION));
			}
		});
	}

	ServiceConnection conn = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			Toast.makeText(ServiceDemoActivity.this, "Connected to the service.", Toast.LENGTH_SHORT).show();
			Log.d(TAG, "onServiceConnected");
		}

		public void onServiceDisconnected(ComponentName name) {
			Toast.makeText(ServiceDemoActivity.this, "Disconnected to the service", Toast.LENGTH_SHORT).show();
			Log.d(TAG, "onServiceDisconnected");
		}
	};

	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy unbindService");
		unbindService(conn);
		super.onDestroy();
	};
}
